package loaders
{
	
	import flash.events.Event;
	import flash.net.URLVariables;
	import flash.system.LoaderContext;
	
	import spark.components.supportClasses.DisplayLayer;
	
	import utils.StringUtils;

	public class LoaderManager
	{
		public function LoaderManager()
		{
		}

		private static var _instance:LoaderManager;

		public static function get Instance():LoaderManager
		{
			if (_instance == null)
			{
				_instance=new LoaderManager();
			}
			return _instance;
		}
		
		private var _loading:Vector.<ILoader> = new Vector.<ILoader>();

		/**
		 * 重写后的loaderManager 一定要用起来足够简单，方便
		 * @param url
		 * @param callback
		 * @param args
		 * @param compressed
		 *
		 */
		public function loadEasy(url:String, callback:Function=null, args:URLVariables=null, compressed:Boolean=false):*
		{
			var loader:ILoader = creatLoaderUrl(url,callback);
			startLoad(loader);
			return loader;
		}
		
		public function startLoad(loader:ILoader):void
		{
			_loading.push(loader);
			loader.addEventListener(LoaderEvent.COMPLETE,onLoadComplete);
			loader.load();
		}
		
		public function get isSomethingLoading():Boolean
		{
			return _loading.length != 0;
		}
		
		protected function onLoadComplete(event:Event):void
		{
			var loader:ILoader = event.currentTarget as ILoader;
			loader.removeEventListener(LoaderEvent.COMPLETE,onLoadComplete);
			_loading.splice(_loading.indexOf(loader),1);
		}
		
		public function creatLoaderUrl(url:String,callback:Function = null):ILoader
		{
			var ext:String=StringUtils.getFileExtendtionFromUrl(url);
			var loader:ILoader;
			switch (ext)
			{
				case "png":
				case "jpg":
				case "jpeg":
				case "gif":
					loader = new DisplayLoader(url,callback);
					break;
				case "swf":
					loader= new SwfLoader(url,callback);
					break;
				case "txt":
				case "xml":
				case "aspx":
				case "ashx":
				case "html":
					loader= new TextLoader(url,callback);
					break;
				default:
					loader=new ByteLoader(url, callback);
			}
			return loader;
		}
	}
}
